package com.mx.web.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
 * App启动的配置，Bean的配置，Mongodb的配置等
 * @author maxu at 2015年10月23日
 */

@EnableWebMvc
@ComponentScan(basePackages = { "com.mx.web" })
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {

	// 配置MongoDB数据库
	private int port = 27017;
	private String host = "localhost";
	private String user = "imxood";
	private String password = "imx123";
	private String database = "imxood";
	private String authenticationDatabase = "admin";

	private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}
	
	@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		
		System.out.println("AppConfig.configureMessageConverters()----------------配置转换器");
        final FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(new MediaType("text", "plain"));
        supportedMediaTypes.add(new MediaType("application", "json"));
        converter.setSupportedMediaTypes(supportedMediaTypes);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }
	
//	这项是必须的,对象与Json字符串的转换
//	@Bean
//	FastJsonHttpMessageConverter converter() {
//		System.out.println("AppConfig.converter()----------------配置转换器");
//        //Set HTTP Message converter using a JSON implementation.
//        FastJsonHttpMessageConverter jsonMessageConverter = new FastJsonHttpMessageConverter();
//        // Add supported media type returned by BI API.
//        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
//        supportedMediaTypes.add(new MediaType("text", "plain"));
//        supportedMediaTypes.add(new MediaType("application", "json"));
//        jsonMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
//        return jsonMessageConverter;
//    }

	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
	
//	/**
//	 * 配置Velocity\
//	 * @return
//	 */
//	@Bean public VelocityEngineFactoryBean velocityEngine(){
//		  VelocityEngineFactoryBean velocityEngineFactoryBean=new VelocityEngineFactoryBean();
//		  Properties velocityProperties=new Properties();
//		  velocityProperties.setProperty("resource.loader","class");
//		  velocityProperties.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//		  velocityEngineFactoryBean.setVelocityProperties(velocityProperties);
//		  return velocityEngineFactoryBean;
//	}
//	
//	@Bean
//	public ViewResolver viewResolver() {
//		VelocityViewResolver resolver = new VelocityViewResolver();
//		resolver.setPrefix("/");
//		resolver.setSuffix(".vm");
//		return resolver;
//	}

	@Bean
	public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
		SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
		Properties mappings = new Properties();
		mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
		mappings.put("org.springframework.dao.DataAccessException",
				"dataAccessFailure");
		mappings.put("org.springframework.transaction.TransactionException",
				"dataAccessFailure");
		exceptionResolver.setExceptionMappings(mappings);
		return exceptionResolver;
	}

	/**
	 * 配置MongoDB的Bean
	 * @return
	 * @throws Exception
	 */
	public @Bean MongoDbFactory mongoDbFactory() throws Exception {
		
		List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
		MongoCredential userCredentials = MongoCredential.createCredential(user, authenticationDatabase, password.toCharArray());
		credentialsList.add(userCredentials);
		return new SimpleMongoDbFactory(new MongoClient(new ServerAddress(host,port), credentialsList), database);
	}

	public @Bean MongoTemplate mongoTemplate() throws Exception {
		logger.info("配置mongoTemplate()...");
		return new MongoTemplate(mongoDbFactory());
	}
}